package com.inventory.controllers;

import com.inventory.entities.Category;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 * CategoryControllerBean handles the CRUD fuctionality of the Category database
 * entity class. This class uses Container managed transactions.
 * @author sithum
 */
@Stateless(mappedName = "CategoryController")
public class CategoryControllerBean implements CategoryControllerRemote {

    /*
     * Injects the specified Persistence unit to the EntityManager associated
     * with the current transaction.
     */
    @PersistenceContext(unitName = "SaicssPU")
    private EntityManager em;

    /**
     * Create records in the Category relation.
     * @param categoryList
     */
    public void create(List<Category> categoryList) {
        for (Category category : categoryList) {
            em.persist(category);
            em.flush();
        }
    }

    public void edit(List<Category> categoryList) {
        for (Category category : categoryList) {
            em.persist(em.merge(category));
        }
    }

    /**
     * Remove set of records from the database Category relation.
     * @param java.util.List
     * @throws java.lang.Exception
     */
    public void delete(List<Object> categoryList) throws Exception {
        for (Object categoryName : categoryList) {
            Category category = findCategoryByName(categoryName.toString());
            if (category != null) {
                em.remove(em.merge(category));
            }
        }
    }

    /**
     * Find a category by a given name.
     * @param java.lang.String categoryName - Name of the category
     * @return com.inventory.entities.Category
     */
    public Category findCategoryByName(String categoryName) {
        Query findByName = em.createNamedQuery("Category.findByCategoryName").setParameter("categoryName", categoryName);
        return (Category) findByName.getSingleResult();
    }

    /**
     * Return all the records in the Category relation.
     * @return
     */
    public List<Category> findAll() {
        return em.createNamedQuery("Category.findAll").getResultList();
    }

    /**
     * Returns true if the category exists.
     * @return
     */
    public boolean isCategoryExists(String categoryName) {
        if (this.findCategoryByName(categoryName) != null) {
            return true;
        } else {
            return false;
        }
    }

    public int count(){
        return Integer.valueOf(em.createNamedQuery("Category.recordCount").getSingleResult().toString()).intValue();
    }

}
